<template>
  <div class="home">
    <ul class="header">
      <li
        v-for="(item, index) in cate"
        :key="item._id"
        @click="change(index, item._id)"
        :class="{ active: currentIndex == index }"
      >
        {{ item.title }}
      </li>
    </ul>

    <van-card
      v-for="item in result"
      :key="item._id"
      :price="item.price"
      :title="item.title"
    >
      <template #footer>
        <van-button size="mini" @click="add(item)">+</van-button>
      </template>
    </van-card>
  </div>
</template>

<script>
// @ is an alias to /src

import { getcate, getlist } from "../utils/http/shopcar";
import { reactive, toRefs, ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";

export default {
  setup(props) {
    const store = useStore();
    //store就相当于是this.$store
    const router = useRouter();
    //就相当于是this.$router
    const data = reactive({
      cate: [],
      list: [],
      //所有的数据
      result: [],
      //筛选过后的数据
    });
    getcate().then((res) => {
      console.log(res);
      data.cate = res.result;
    });
    //tab分类数据
    getlist().then((res) => {
      data.list = res.result;
      change(0, "59f1e1ada1da8b15d42234e9");
      //拿到数据之后执行change进入页面就有第一个分类的数据
    });
    //列表数据

    const currentIndex = ref(0);
    //当前点击的下标

    const change = (i, id) => {
      currentIndex.value = i;
      //vue3没有过滤器了（过滤器是那个管道符|） 不是说数组没有过滤方法了
      data.result = data.list.filter((item) => {
        return item.cid == id;
      });
      //根据分类id进行过滤保存给result
    };
    //保存点击的下标

    const add = (item) => {
      store.commit("add", item);
      router.push("/about");
      //路由跳转 编程式导航 就是之前的this.$router.push
    };

    return { ...toRefs(data), change, currentIndex, add };
  },
  // setup函数就相当于之前的生命周期函数beforecreate和created 直接放在setup中就行
};
</script>
<style lang="scss">
.header {
  width: 100%;
  height: 40px;
  display: flex;
  background: rgb(160, 75, 209);
  li {
    color: #fff;
    font-size: 20px;
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
  }
  .active {
    background: greenyellow;
  }
}
</style>
